<?php

namespace App\Http\Controllers;

use App\Models\Picture;
use App\Models\Record;
use Illuminate\Http\Request;

class HomeController extends Controller
{
    public function index(Request $request)
    {
        $ip = $request->getClientIp();
        $ua = $request->header('user-agent');
        $page = $request->get('page', 1);
        session(['page' => $page]);
        $items = Picture::orderBy('datetime', 'desc')->paginate(12);
        foreach ($items as $item) {
            $item['url'] = str_replace('1920x1080', '400x240', $item['url']);
            // 判断当前用户是否点赞
            $record = Record::where('ip', $ip)
                ->where('ua', $ua)->where('picture_id', $item['id'])
                ->where('type', 3)->first();
            if (empty($record)) {
                $item['hasLike'] = false;
            } else {
                $item['hasLike'] = true;
            }
        }

        return view('home', compact(
            'items'
        ));
    }

    public function detail(Request $request, $id)
    {
        $item = Picture::find($id);
        $next = Picture::where('id', '>', $id)->first();
        $last = Picture::where('id', '<', $id)->orderBy('id', 'desc')->first();
        $view = $this->checkRecord($request, $id);
        if (!$view) {
            $item['view'] += 1;
            $item->save();
        }
        return view('detail', compact(
            'item',
            'last',
            'next'
        ));
    }

    public function record(Request $request, $id)
    {
        $item = Picture::find($id);
        $types = ['', 'view', 'down', 'like'];
        $type = $request->get('type', 1);
        $flag = $this->checkRecord($request, $id, $type);
        if (!$flag) {
            $item[$types[$type]] += 1;
            $item->save();
        }
    }

    private function checkRecord($request, $id, $type = 1)
    {
        $types = ['', 'view', 'down', 'like'];
        $sessionKey = $id . $types[$type];
        if (session($sessionKey, false) == true) {
            return true;
        }
        $ip = $request->getClientIp();
        $ua = $request->header('user-agent');
        $item = Record::where('ip', $ip)
            ->where('ua', $ua)
            ->where('picture_id', $id)
            ->where('type', $type)
            ->first();
        if (empty($item)) {
            $item = new Record();
            $item['picture_id'] = $id;
            $item['type'] = $type;
            $item['ip'] = $ip;
            $item['ua'] = $ua;
            $item->save();
            session([$sessionKey => true]);
            return false;
        }
        session([$sessionKey => true]);
        return true;
    }
}
